#!/usr/local/bin/guile3.0 \
-e main -s
!#

;;; This is a simple script that automounts your usb stick to /mnt/usb
;; see man hotplugd for more info
;;;
;;; To easily test this script execute
;;; doas ./attach 2 "sd2"
;;;
;;; TODO make it more robust:
;;; https://github.com/a12n/openbsd-hotplug/blob/master/hotplug.pl
;;; Should I check to make sure the label is "USB Flash Drive"?
;;; or is "USB Flash Drive" not guarenteed to be there all the time
;;; for all USB Flash Drives?

(use-modules (rnrs io ports))
(use-modules (ice-9 popen))

(define (fs-type-and-partition name)
  (let* ((port (open-input-pipe
                (string-append "/sbin/disklabel -t " name " 2>&1 | \
                       grep -e ':t[ab]=' -e ':t[d-p]'| cut -f 4 -d ':'")))
         (str (string-drop-right (get-line port) 1)))
    (close-pipe port)
    str))

(define (main args)
  (define class (car (cdr args)))
  (define name (car (cddr args)))

  ;; when this is a disk drive with a filesystem of msdos, mount it
  (when (and (string=? "2" class)
             (fs-type-msdos? name))
    (display "mounting")
    (system* "mount" "-o" "rw,nodev,noexec,nodev" (string-append "/dev/" name "i") "/mnt/usb")))
